package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

/**
 * 鏁版嵁搴撹闂伐鍏风被
 * 
 * @author acer
 *
 */
public class BaseDao {

	public static Connection conn;
	protected PreparedStatement statement;
	protected ResultSet rs;

	private static String driver;
	private static String url;
	private static String username;
	private static String password;

	/**
	 * 闈欐�佸潡 璇诲彇閰嶇疆鏂囦欢
	 * 鏈�鏃╁姞杞� 鍙姞杞戒竴娆�
	 */
	static {
		try {
			Properties propertie = new Properties();
			// 鍔犺浇閰嶇疆鏂囦欢
			propertie.load(BaseDao.class.getClassLoader().getResourceAsStream("database.properties"));

			//璇诲彇姣忎釜灞炴�ц祴鍊�
			driver = propertie.getProperty("driver");
			url = propertie.getProperty("url");
			username = propertie.getProperty("username");
			password = propertie.getProperty("password");
		} catch (Exception e) {
			System.out.println("鍔犺浇閰嶇疆鏂囦欢澶辫触");
		}
	}

	/**
	 * 鑾峰彇杩炴帴
	 * 
	 * @return
	 */
	public Connection getConnection() {
		try {
			//jdbc
			if(conn ==null){
//				//鍒涘缓杩炴帴
				Class.forName(driver);
				conn =  DriverManager.getConnection(url, username, password);
			
				//dataSource杩炴帴姹� tomcat杩愯
//				Context context = new InitialContext();
//				DataSource dataSource  =(DataSource)context.lookup("java:comp/env/jdbc/news");
//				conn = dataSource.getConnection();
			}
			//鐩存帴杩斿洖杩炴帴
			return conn;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 鎵ц澧炲垹鏀�
	 * 
	 * @param sql
	 * @param parms
	 *            0 - n涓弬鏁� 浼氳嚜鍔ㄥ皝瑁呮垚鏁扮粍
	 * @return
	 */
	public int executeUpdate(String sql, Object... parms) {
		try {
			conn = getConnection();
			statement = conn.prepareStatement(sql);
			// 璁剧疆鍙傛暟
			if (parms != null) {
				for (int i = 0; i < parms.length; i++) {
					statement.setObject(i + 1, parms[i]);
				}
			}
			
			return statement.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			//closeAll(conn, statement, rs);
		}
		return 0;
	}

	/**
	 * 鎵ц鏌ヨ
	 * 
	 * @param sql
	 * @param parms
	 * @return
	 */
	public ResultSet executeQuery(String sql, Object... parms) {
		try {
			conn = getConnection();
			statement = conn.prepareStatement(sql);
			// 璁剧疆鍙傛暟
			if (parms != null) {
				for (int i = 0; i < parms.length; i++) {
					statement.setObject(i + 1, parms[i]);
				}
			}
			return statement.executeQuery();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 鍏抽棴
	 * 
	 * @param conn
	 * @param statement
	 * @param rs
	 */
	public void closeAll(Connection conn, PreparedStatement statement, ResultSet rs) {
		try {
			if (rs != null)
				rs.close();
			if (statement != null)
				statement.close();
			if (conn != null)
				conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
